﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0065)http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""><HTML><HEAD><META 
content="IE=10.000" http-equiv="X-UA-Compatible">
 
<META http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<TITLE>Android: NDK编程入门笔记 - Braincol - 博客园</TITLE> <LINK href="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/common.css" 
rel="stylesheet" type="text/css"> <LINK id="MainCss" href="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/style.css" 
rel="stylesheet" type="text/css"> <LINK href="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/common2.css" 
rel="stylesheet" type="text/css"> <LINK href="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/shStyle.css" 
rel="stylesheet" type="text/css"> <LINK title="RSS" href="http://www.cnblogs.com/hibraincol/rss" 
rel="alternate" type="application/rss+xml"> <LINK title="RSD" href="http://www.cnblogs.com/hibraincol/rsd.xml" 
rel="EditURI" type="application/rsd+xml"> <LINK href="http://www.cnblogs.com/hibraincol/wlwmanifest.xml" 
rel="wlwmanifest" type="application/wlwmanifest+xml"> 
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/jquery.js" type="text/javascript"></SCRIPT>
  
<SCRIPT type="text/javascript">
var currentBlogApp = 'hibraincol';
</SCRIPT>
 
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/common.js" type="text/javascript"></SCRIPT>
 
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/json2.js" type="text/javascript"></SCRIPT>
 
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/syntaxHighlighter.js" type="text/javascript"></SCRIPT>
 
<META name="GENERATOR" content="MSHTML 10.00.9200.16635"></HEAD> 
<BODY><A name="top"></A> <!--done--> 
<DIV id="banner">
<DIV id="bnr_pic"><!--done--> 
<DIV class="header">
<DIV class="headerText"><A class="headermaintitle" id="Header1_HeaderTitle" 
href="http://www.cnblogs.com/hibraincol/">Hibraincol</A><BR></DIV>
<DIV class="headerDis">快乐代码！</DIV></DIV></DIV></DIV>
<DIV id="main"><!-- left starts -->	 
<DIV id="left">
<DIV id="left_border">
<DIV id="mystats"><BR><!--done--> 
<DIV class="blogStats">随笔- 40&nbsp; 文章- 0&nbsp; 评论- 57&nbsp; </DIV></DIV>
<DIV id="mylinks"><!--done--> <A class="menu" id="MyLinks1_HomeLink" href="http://www.cnblogs.com/">博客园</A>&nbsp;&nbsp;<A 
class="menu" id="MyLinks1_MyHomeLink" 
href="http://www.cnblogs.com/hibraincol/">首页</A>&nbsp;&nbsp;<A class="menu" id="MyLinks1_NewPostLink" 
href="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx?opt=1" rel="nofollow">新随笔</A>&nbsp;&nbsp;<A 
class="menu" id="MyLinks1_NewArticleLink" href="http://www.cnblogs.com/EnterMyBlog.aspx?NewArticle=1">新文章</A>&nbsp;&nbsp;<A 
class="menu" id="MyLinks1_ContactLink" accesskey="9" href="http://space.cnblogs.com/msg/send/Braincol" 
rel="nofollow">联系</A>&nbsp;&nbsp;<A class="menu" id="MyLinks1_Admin" href="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx" 
rel="nofollow">管理</A>&nbsp;&nbsp;<A class="menu" id="MyLinks1_Syndication" href="http://www.cnblogs.com/hibraincol/rss">订阅</A>&nbsp;<A 
id="MyLinks1_XMLLink" href="http://www.cnblogs.com/hibraincol/rss"><IMG alt="订阅" 
src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/xml.gif"></A></DIV>
<DIV id="topics"><!--done--> 
<DIV class="post">
<DIV class="postTitle"><A class="postTitle2" id="cb_post_title_url" href="http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html">Android: 
NDK编程入门笔记</A>	 </DIV>
<DIV id="cnblogs_post_body">
<P><STRONG><FONT color="#000000" size="3">为何要用到NDK?</FONT></STRONG></P>
<P>概括来说主要分为以下几种情况：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000">1. 
  代码的保护，由于apk的java层代码很容易被反编译，而C/C++库反汇难度较大。</FONT></P>
  <P><FONT color="#000000">2. 
在NDK中调用第三方C/C++库，因为大部分的开源库都是用C/C++代码编写的。</FONT></P>
  <P><FONT color="#000000">3. 便于移植，用C/C++写得库可以方便在其他的嵌入式平台上再次使用。</FONT></P>
  <P><FONT color="#000000"></FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" size="3"><STRONG>下面就介绍下Android 
NDK的入门学习过程：</STRONG></FONT></P>
<P>入门的最好办法就是学习Android自带的例子， 这里就通过学习Android的NDK自带的demo程序：hello-jni来达到这个目的。</P>
<P><FONT color="#000000" size="3"><STRONG>一、 开发环境的搭建</STRONG></FONT></P>
<OL>
  <LI><FONT color="#000000">android的NDK开发需要在linux下进行： 
  因为需要把C/C++编写的代码生成能在arm上运行的.so文件，这就需要用到交叉编译环境，而交叉编译需要在linux系统下才能完成。</FONT> 
</LI>
  <LI><FONT color="#000000">安装android-ndk开发包，这个开发包可以在google android 官网下载： 
  通过这个开发包的工具才能将android jni 的C/C++的代码编译成库</FONT> </LI>
  <LI><FONT color="#000000">android应用程序开发环境： 包括eclipse、java、 android sdk、 
  adt等。</FONT> </LI></OL>
<P>如何下载和安装android-ndk我这里就不啰嗦了，安装完之后，需要将android-ndk的路劲加到环境变量PATH中：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000"><FONT 
  style="background-color: rgb(204, 204, 204);"></FONT></FONT><FONT color="#000000">sudo 
  gedit /etc/environment</FONT></P></BLOCKQUOTE>
<P>在environment的PATH环境变量中添加你的android-ndk的安装路劲，然后再让这个更改的环境变量立即生效：</P>
<BLOCKQUOTE>
  <P><FONT style="background-color: rgb(204, 204, 204);"></FONT>&nbsp;<FONT 
  color="#000000">source&nbsp; /etc/environment</FONT></P></BLOCKQUOTE>
<P>经过了上述步骤，在命令行下敲： </P>
<BLOCKQUOTE>
  <P><FONT color="#000000"></FONT><FONT 
color="#000000">ndk-bulid</FONT></P></BLOCKQUOTE>
<P>弹出如下的错误，而不是说ndk-build not found，就说明ndk环境已经安装成功了。</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">Android NDK: Could not find application project directory 
  !&nbsp;&nbsp;&nbsp; <BR>Android NDK: Please define the NDK_PROJECT_PATH 
  variable to point to it.&nbsp;&nbsp;&nbsp; 
  <BR>/home/braincol/workspace/android/android-ndk-r5/build/core/build-local.mk:85: 
  *** Android NDK: Aborting&nbsp;&nbsp;&nbsp; .&nbsp; 
Stop.</FONT></P></BLOCKQUOTE>
<P><STRONG></STRONG>&nbsp;</P>
<P><FONT color="#000000" size="3"><STRONG>二、代码的编写</STRONG></FONT></P>
<P><FONT color="#000000" size="3"><STRONG>1.首先是写java代码</STRONG></FONT></P>
<P>建立一个Android应用工程HelloJni，创建HelloJni.java文件：</P>
<P><EM><FONT 
style="background-color: rgb(204, 204, 204);"></FONT></EM><EM>HelloJni.java 
:</EM></P>
<DIV id="codeSnippetWrapper">
<PRE id="codeSnippet" style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'><SPAN style="color: rgb(0, 128, 0);">/*</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Copyright (C) 2009 The Android Open Source Project</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Licensed under the Apache License, Version 2.0 (the "License");</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * you may not use this file except in compliance with the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * You may obtain a copy of the License at</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *      http://www.apache.org/licenses/LICENSE-2.0</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Unless required by applicable law or agreed to in writing, software</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * distributed under the License is distributed on an "AS IS" BASIS,</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * See the License for the specific language governing permissions and</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * limitations under the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> */</SPAN><BR><SPAN style="color: rgb(0, 0, 255);">package</SPAN> com.example.hellojni;<BR><BR><SPAN style="color: rgb(0, 0, 255);">import</SPAN> android.app.Activity;<BR><SPAN style="color: rgb(0, 0, 255);">import</SPAN> android.widget.TextView;<BR><SPAN style="color: rgb(0, 0, 255);">import</SPAN> android.os.Bundle;<BR><BR><BR><SPAN style="color: rgb(0, 0, 255);">public</SPAN> <SPAN style="color: rgb(0, 0, 255);">class</SPAN> HelloJni <SPAN style="color: rgb(0, 0, 255);">extends</SPAN> Activity<BR>{<BR>    <SPAN style="color: rgb(0, 128, 0);">/** Called when the activity is first created. */</SPAN><BR>    @Override<BR>    <SPAN style="color: rgb(0, 0, 255);">public</SPAN> <SPAN style="color: rgb(0, 0, 255);">void</SPAN> onCreate(Bundle savedInstanceState)<BR>    {<BR>        <SPAN style="color: rgb(0, 0, 255);">super</SPAN>.onCreate(savedInstanceState);<BR><BR>        <SPAN style="color: rgb(0, 128, 0);">/* Create a TextView and set its content.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">         * the text is retrieved by calling a native</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">         * function.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">         */</SPAN><BR>        TextView  tv = <SPAN style="color: rgb(0, 0, 255);">new</SPAN> TextView(<SPAN style="color: rgb(0, 0, 255);">this</SPAN>);<BR>        tv.setText( stringFromJNI() );<BR>        setContentView(tv);<BR>    }<BR><BR>    <SPAN style="color: rgb(0, 128, 0);">/* A native method that is implemented by the</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * 'hello-jni' native library, which is packaged</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * with this application.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     */</SPAN><BR>    <SPAN style="color: rgb(0, 0, 255);">public</SPAN> <SPAN style="color: rgb(0, 0, 255);">native</SPAN> String  stringFromJNI();<BR><BR>    <SPAN style="color: rgb(0, 128, 0);">/* This is another native method declaration that is *not*</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * implemented by 'hello-jni'. This is simply to show that</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * you can declare as many native methods in your Java code</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * as you want, their implementation is searched in the</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * currently loaded native libraries only the first time</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * you call them.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * Trying to call this function will result in a</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * java.lang.UnsatisfiedLinkError exception !</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     */</SPAN><BR>    <SPAN style="color: rgb(0, 0, 255);">public</SPAN> <SPAN style="color: rgb(0, 0, 255);">native</SPAN> String  unimplementedStringFromJNI();<BR><BR>    <SPAN style="color: rgb(0, 128, 0);">/* this is used to load the 'hello-jni' library on application</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * startup. The library has already been unpacked into</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * /data/data/com.example.HelloJni/lib/libhello-jni.so at</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     * installation time by the package manager.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">     */</SPAN><BR>    <SPAN style="color: rgb(0, 0, 255);">static</SPAN> {<BR>        System.loadLibrary(<SPAN style="color: rgb(0, 96, 128);">"hello-jni"</SPAN>);<BR>    }<BR>}</PRE><BR></DIV>
<P>这段代码很简单，注释也很清晰，这里只提两点：<FONT color="#000000">:</FONT></P>
<BLOCKQUOTE>
  <P><FONT color="#000000">static{        <BR>System.loadLibrary(<SPAN style="color: rgb(0, 96, 128);">"hello-jni"</SPAN>); 
         <BR>}</FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" 
style="background-color: rgb(255, 255, 255);">表明程序开始运行的时候会加载hello-jni, 
static区声明的代码会先于onCreate方法执行。如果你的程序中有多个类，而且如果HelloJni这个类不是你应用程序的入口，那么hello-jni（完整的名字是libhello-jni.so）这个库会在第一次使用HelloJni这个类的时候加载。</FONT></P>
<BLOCKQUOTE>
  <P><FONT color="#000000">public native String stringFromJNI();        
  <BR>public native String unimplementedStringFromJNI(); </FONT><FONT color="#000000"></FONT></P><FONT 
  color="#000000"></FONT></BLOCKQUOTE>
<P><FONT color="#000000">可以看到这两个方法的声明中有 native 关键字， 
这个关键字表示这两个方法是本地方法，也就是说这两个方法是通过本地代码（C/C++）实现的，在java代码中仅仅是声明。</FONT></P>
<P>用eclipse编译该工程，生成相应的.class文件，这步必须在下一步之前完成，因为生成.h文件需要用到相应的.class文件。</P>
<P>&nbsp;</P>
<P><STRONG><FONT color="#000000" size="3">2. 编写相应的C/C++代码</FONT></STRONG></P>
<P>刚开始学的时候，有个问题会让人很困惑，相应的C/C++代码如何编写，函数名如何定义？ 
这里讲一个方法，利用javah这个工具生成相应的.h文件，然后根据这个.h文件编写相应的C/C++代码。</P>
<P><STRONG><FONT color="#000000">2.1 生成相应.h文件：</FONT></STRONG></P>
<P>就拿我这的环境来说，首先在终端下进入刚刚建立的HelloJni工程的目录：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~$ cd workspace/android/NDK/hello-jni/ 
  </FONT><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT></P></BLOCKQUOTE>ls查看工程文件  
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls        
  <BR>AndroidManifest.xml&nbsp; assets&nbsp; bin&nbsp; default.properties&nbsp; 
  gen&nbsp; res&nbsp; src</FONT><FONT color="#d16349">       <BR></FONT><FONT 
  color="#d16349"></FONT></P></BLOCKQUOTE>
<P>可以看到目前仅仅有几个标准的android应用程序的文件（夹）。</P>
<P>首先我们在工程目录下建立一个jni文件夹：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ mkdir jni   
       <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls        
  <BR>AndroidManifest.xml&nbsp; assets&nbsp; bin&nbsp; default.properties&nbsp; 
  gen&nbsp; jni&nbsp; res&nbsp; src        <BR></FONT><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT></P></BLOCKQUOTE><FONT 
color="#333333"></FONT> 
<P>下面就可以生成相应的.h文件了：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ javah 
  -classpath bin -d jni com.example.hellojni.HelloJni        <BR></FONT><FONT 
  color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT></P></BLOCKQUOTE>
<P>-classpath bin：表示类的路劲</P>
<P>-d jni: 表示生成的头文件存放的目录</P>
<P>com.example.hellojni.HelloJni 则是完整类名</P>
<P>这一步的成功要建立在已经在 bin/com/example/hellojni/&nbsp; 目录下生成了 HelloJni.class的基础之上。</P>
<P>现在可以看到jni目录下多了个.h文件：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd jni/     
     <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ ls        
  <BR></FONT><FONT 
color="#000000">com_example_hellojni_HelloJni.h</FONT></P></BLOCKQUOTE><FONT 
color="#c0504d">
<P><FONT color="#000000">我们来看看com_example_hellojni_HelloJni.h的内容：</FONT></P>
<P><EM><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT></EM><EM><FONT color="#000000">com_example_hellojni_HelloJni.h 
: </FONT></EM></P></FONT><FONT color="#c0504d">   
<PRE id="codeSnippet" style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'><SPAN style="color: rgb(0, 128, 0);">/* DO NOT EDIT THIS FILE - it is machine generated */</SPAN><BR><SPAN style="color: rgb(204, 102, 51);">#include</SPAN> &lt;jni.h&gt;<BR><SPAN style="color: rgb(0, 128, 0);">/* Header for class com_example_hellojni_HelloJni */</SPAN><BR><BR><SPAN style="color: rgb(204, 102, 51);">#ifndef</SPAN> _Included_com_example_hellojni_HelloJni<BR><SPAN style="color: rgb(204, 102, 51);">#define</SPAN> _Included_com_example_hellojni_HelloJni<BR><SPAN style="color: rgb(204, 102, 51);">#ifdef</SPAN> __cplusplus<BR><SPAN style="color: rgb(0, 0, 255);">extern</SPAN> <SPAN style="color: rgb(0, 96, 128);">"C"</SPAN> {<BR><SPAN style="color: rgb(204, 102, 51);">#endif</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">/*</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Class:     com_example_hellojni_HelloJni</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Method:    stringFromJNI</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Signature: ()Ljava/lang/String;</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> */</SPAN><BR>JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI<BR>  (JNIEnv *, jobject);<BR><BR><SPAN style="color: rgb(0, 128, 0);">/*</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Class:     com_example_hellojni_HelloJni</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Method:    unimplementedStringFromJNI</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Signature: ()Ljava/lang/String;</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> */</SPAN><BR>JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI<BR>  (JNIEnv *, jobject);<BR><BR><SPAN style="color: rgb(204, 102, 51);">#ifdef</SPAN> __cplusplus<BR>}<BR><SPAN style="color: rgb(204, 102, 51);">#endif</SPAN><BR><SPAN style="color: rgb(204, 102, 51);">#endif</SPAN></PRE>
<P><FONT color="#000000">上面代码中的JNIEXPORT 和 JNICALL 
是jni的宏，在android的jni中不需要，当然写上去也不会有错。</FONT></P>
<P><FONT color="#000000">从上面的源码中可以看出这个函数名那是相当的长啊。。。。 不过还是很有规律的， 
完全按照：java_pacakege_class_mathod 形式来命名。</FONT></P>
<P><FONT color="#000000">也就是说：</FONT></P>
<P><FONT color="#ffffff"></FONT></P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">Hello.java中 stringFromJNI() 方法对应于 C/C++中的 
  Java_com_example_hellojni_HelloJni_stringFromJNI() 方法</FONT></P>
  <P><FONT color="#000000">HelloJni.java中的 unimplementedStringFromJNI() 方法对应于 
  C/C++中的 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI() 方法     
       <BR></FONT><FONT color="#000000" style="background-color: rgb(204, 204, 204);"></FONT></P></BLOCKQUOTE>
<P><FONT color="#000000">注意下其中的注释：</FONT></P>
<BLOCKQUOTE>
  <P><FONT color="#000000"><FONT 
  style="background-color: rgb(204, 204, 204);"><SPAN style="color: rgb(0, 128, 0);"><FONT 
  color="#000000"></FONT></SPAN></FONT></FONT><FONT color="#000000"><SPAN style="color: rgb(0, 128, 0);"><FONT 
  color="#000000">Signature: ()Ljava/lang/String;</FONT></SPAN>         
  <BR></FONT><FONT color="#000000"><FONT style="background-color: rgb(204, 204, 204);"></FONT></FONT></P></BLOCKQUOTE>
<P><FONT color="#000000">()Ljava/lang/String;</FONT></P>
<P><FONT color="#000000">()表示函数的参数为空（这里为空是指除了JNIEnv *, jobject 
这两个参数之外没有其他参数，JNIEnv*, 
jobject是所有jni函数必有的两个参数，分别表示jni环境和对应的java类（或对象）本身），</FONT></P>
<P><FONT color="#000000">Ljava/lang/String; 表示函数的返回值是java的String对象。</FONT></P>
<P>&nbsp;</P>
<P><FONT color="#000000"><STRONG>2.2 编写相应的.c文件：</STRONG></FONT></P>
<P><EM><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT></EM><EM><FONT color="#000000">hello-jni.c 
:</FONT></EM></P></FONT><FONT color="#c0504d">   
<DIV id="codeSnippetWrapper">
<PRE id="codeSnippet" style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'><SPAN style="color: rgb(0, 128, 0);">/*</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Copyright (C) 2009 The Android Open Source Project</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Licensed under the Apache License, Version 2.0 (the "License");</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * you may not use this file except in compliance with the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * You may obtain a copy of the License at</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *      http://www.apache.org/licenses/LICENSE-2.0</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * Unless required by applicable law or agreed to in writing, software</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * distributed under the License is distributed on an "AS IS" BASIS,</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * See the License for the specific language governing permissions and</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * limitations under the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> */</SPAN><BR><SPAN style="color: rgb(204, 102, 51);">#include</SPAN> &lt;string.h&gt;<BR><SPAN style="color: rgb(204, 102, 51);">#include</SPAN> &lt;jni.h&gt;<BR><BR><SPAN style="color: rgb(0, 128, 0);">/* This is a trivial JNI example where we use a native method</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * to return a new VM String. See the corresponding Java source</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> * file located at:</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> *   apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"> */</SPAN><BR>jstring<BR>Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,<BR>                                                  jobject thiz )<BR>{<BR>    <SPAN style="color: rgb(0, 0, 255);">return</SPAN> (*env)-&gt;NewStringUTF(env, <SPAN style="color: rgb(0, 96, 128);">"Hello from JNI !"</SPAN>);<BR>}</PRE></DIV>
<P><FONT 
color="#000000">这里只是实现了Java_com_example_hellojni_HelloJni_stringFromJNI方法，而 
Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI 
方法并没有实现，因为在HelloJni.java中只调用了stringFromJNI()方法，所以unimplementedStringFromJNI()方法没有实现也没关系，不过建议最好还是把所有java中定义的本地方法都实现了，写个空函数也行啊。。。有总比没有好。</FONT></P>
<P><FONT color="#000000">Java_com_example_hellojni_HelloJni_stringFromJNI() 
函数只是简单的返回了一个内容为 "Hello from JNI !" 的jstring对象（对应于java中的String对象）。</FONT></P>
<P><FONT 
color="#000000">hello-jni.c文件已经编写好了，现在可以把com_example_hellojni_HelloJni.h文件给删了，当然留着也行，只是我还是习惯把不需要的文件给清理干净了。</FONT></P>
<P><FONT color="#000000"></FONT>&nbsp;</P>
<P><STRONG><FONT color="#000000" size="3">3. 编译hello-jni.c 
生成相应的库</FONT></STRONG></P>
<P><FONT color="#000000"><STRONG>3.1 编写Android.mk文件</STRONG></FONT></P>
<P><FONT color="#000000">在jni目录下（即hello-jni.c 同级目录下）新建一个Android.mk文件，<FONT 
style="background-color: rgb(204, 204, 204);"></FONT></FONT><FONT color="#000000">Android.mk 
</FONT><FONT color="#000000"><FONT 
style="background-color: rgb(204, 204, 204);"></FONT>文件是Android 的 
makefile文件，内容如下：</FONT></P>
<DIV>
<PRE id="codeSnippet" style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'><SPAN style="color: rgb(0, 128, 0);"># Copyright (C) 2009 The Android Open Source Project</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">#</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># Licensed under the Apache License, Version 2.0 (the "License");</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># you may not use this file except in compliance with the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># You may obtain a copy of the License at</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">#</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">#      http://www.apache.org/licenses/LICENSE-2.0</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">#</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># Unless required by applicable law or agreed to in writing, software</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># distributed under the License is distributed on an "AS IS" BASIS,</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># See the License for the specific language governing permissions and</SPAN><BR><SPAN style="color: rgb(0, 128, 0);"># limitations under the License.</SPAN><BR><SPAN style="color: rgb(0, 128, 0);">#</SPAN><BR>LOCAL_PATH := $(call my-dir)<BR><BR><SPAN style="color: rgb(0, 0, 255);">include</SPAN> $(CLEAR_VARS)<BR><BR>LOCAL_MODULE    := hello-jni<BR>LOCAL_SRC_FILES := hello-jni.c<BR><BR><SPAN style="color: rgb(0, 0, 255);">include</SPAN> $(BUILD_SHARED_LIBRARY)</PRE></DIV>
<DIV><FONT color="#ffffff">这个Androd.mk文件很短，下面我们来逐行解释下：</FONT></DIV>
<P><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT><FONT 
color="#000000">LOCAL_PATH := $(call my-dir) </FONT></P></FONT><FONT color="#c0504d"> 
  
<BLOCKQUOTE>
  <P><FONT color="#000000">一个Android.mk 
  文件首先必须定义好LOCAL_PATH变量。它用于在开发树中查找源文件。在这个例子中，宏函数’my-dir’, 
  由编译系统提供，用于返回当前路径（即包含Android.mk file文件的目录）。</FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT><FONT 
color="#000000">include $( CLEAR_VARS) </FONT></P></FONT><FONT color="#c0504d">  
 
<BLOCKQUOTE>
  <P><FONT color="#000000">CLEAR_VARS由编译系统提供，指定让GNU MAKEFILE为你清除许多LOCAL_XXX变量（例如 
  LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, 等等...),          
  <BR>除LOCAL_PATH 。这是必要的，因为所有的编译控制文件都在同一个GNU 
MAKE执行环境中，所有的变量都是全局的。</FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT><FONT 
color="#000000">LOCAL_MODULE := hello-jni</FONT></P></FONT><FONT 
color="#c0504d">   
<BLOCKQUOTE>
  <P><FONT 
  color="#000000">编译的目标对象，LOCAL_MODULE变量必须定义，以标识你在Android.mk文件中描述的每个模块。名称必须是唯一的，而且不包含任何空格。</FONT></P>
  <P><FONT 
  color="#000000">注意：编译系统会自动产生合适的前缀和后缀，换句话说，一个被命名为'hello-jni'的共享库模块，将会生成'libhello-jni.so'文件。 
  </FONT></P>
  <P><FONT color="#000000">重要注意事项： </FONT></P>
  <P><FONT color="#000000">如果你把库命名为‘libhello-jni’，编译系统将不会添加任何的lib前缀，也会生成 
  'libhello-jni.so'，这是为了支持来源于Android平台的源代码的Android.mk文件，如果你确实需要这么做的话。</FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT><FONT 
color="#000000">LOCAL_SRC_FILES := hello-jni.c</FONT></P></FONT><FONT color="#c0504d"> 
  
<BLOCKQUOTE>
  <P><FONT 
  color="#000000">LOCAL_SRC_FILES变量必须包含将要编译打包进模块中的C或C++源代码文件。注意，你不用在这里列出头文件和包含文件，因为编译系统将会自动为你找出依赖型的文件；仅仅列出直接传递给编译器的源代码文件就好。 
  </FONT></P>
  <P><FONT color="#000000">注意，默认的C++源码文件的扩展名是’.cpp’. 
  指定一个不同的扩展名也是可能的，只要定义LOCAL_DEFAULT_CPP_EXTENSION变量，不要忘记开始的小圆点（也就是’.cxx’,而不是’cxx’）</FONT></P></BLOCKQUOTE>
<P><FONT color="#000000" 
style="background-color: rgb(204, 204, 204);"></FONT><FONT 
color="#000000">include $(BUILD_SHARED_LIBRARY) </FONT></P></FONT><FONT color="#c0504d"> 
  
<BLOCKQUOTE>
  <P><FONT color="#000000">BUILD_SHARED_LIBRARY表示编译生成共享库，是编译系统提供的变量，指向一个GNU 
  Makefile脚本，负责收集自从上次调用'include 
  $(CLEAR_VARS)'以来，定义在LOCAL_XXX变量中的所有信息，并且决定编译什么，如何正确地去做。还有 
  BUILD_STATIC_LIBRARY变量表示生成静态库：lib$(LOCAL_MODULE).a， BUILD_EXECUTABLE 
  表示生成可执行文件。</FONT></P></BLOCKQUOTE>
<DIV>&nbsp;</DIV>
<DIV><STRONG><FONT color="#000000">3.2 生成.so共享库文件</FONT></STRONG></DIV>
<DIV><FONT color="#000000">Andro文件已经编写好了，现在可以用android NDK开发包中的 
ndk-build脚本生成对应的.so共享库了，方法如下：</FONT></DIV>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ cd ..   
         <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls          
  <BR>AndroidManifest.xml&nbsp; assets&nbsp; bin&nbsp; default.properties&nbsp; 
  gen&nbsp; jni&nbsp; libs&nbsp; obj&nbsp; res&nbsp; src          
  <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ndk-build          
  <BR>Gdbserver&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : [arm-linux-androideabi-4.4.3] 
  libs/armeabi/gdbserver          
  <BR>Gdbsetup&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : libs/armeabi/gdb.setup      
      <BR>Install&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : libhello-jni.so 
  =&gt; libs/armeabi/libhello-jni.so          <BR></FONT><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT></P></BLOCKQUOTE></FONT> 
<P>可以看到已经正确的生成了libhello-jni.so共享库了， 我们去 libs/armeabi/ 目录下看看：</P>
<BLOCKQUOTE>
  <P><FONT color="#000000" 
  style="background-color: rgb(204, 204, 204);"></FONT><FONT 
  color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd libs/    
      <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ ls        
  <BR>armeabi        <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ 
  cd armeabi/        
  <BR>braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs/armeabi$ ls        
  <BR>gdbserver&nbsp; gdb.setup&nbsp; libhello-jni.so</FONT></P></BLOCKQUOTE>
<P><STRONG><FONT color="#000000" size="3">4. 
在eclipse重新编译HelloJni工程，生成apk</FONT></STRONG></P>
<P>eclipse中刷新下HelloJni工程，重新编译生成apk，libhello-jni.so共享库会一起打包在apk文件内。</P>
<P>在模拟器中看看运行结果：</P>
<P><FONT color="#c0504d"><A href="http://images.cnblogs.com/cnblogs_com/hibraincol/201105/201105302329215965.png"><IMG 
width="318" height="388" title="hello-jni" style="border-width: 0px; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" 
alt="hello-jni" src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/201105302329223390.png" 
border="0"></A></FONT></P>
<P><FONT color="#c0504d"><BR></FONT></P></DIV>
<DIV id="MySignature"></DIV>
<SCRIPT type="text/javascript">
var isLogined = false;
var cb_blogId = 75839;
var cb_entryId = 2063847;
var cb_blogApp = currentBlogApp;
var cb_blogUserGuid = "b6df09fc-38bf-df11-ac81-842b2b196315";
var cb_entryCreatedDate = '2011/5/30 23:29:00';
var enableGoogleAd = true;
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
</SCRIPT>
 
<DIV class="clear"></DIV>
<DIV id="blog_post_info_block">
<DIV id="blog_post_info"></DIV>
<DIV class="clear"></DIV>
<DIV id="post_next_prev"></DIV></DIV>
<SCRIPT type="text/javascript">
    //SyntaxHighlighter.config.strings.expandSource = '<span><img src="http://static.cnblogs.com/images/expand-code.gif" alt="" class="expand-code-icon"/>View Code</span>';
    $(function () {  
        loadViewCount(cb_entryId);
        fixPostBodyFormat();
        loadAdUnderPost();
        loadBlogSignature();
        LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
        GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);        
        GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);        
    });
</SCRIPT>
	 
<DIV class="postDesc"><IMG align="absmiddle" src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/speech.gif">&nbsp;posted 
on <SPAN id="post-date">2011-05-30 23:29</SPAN> <A href="http://www.cnblogs.com/hibraincol/">Braincol</A> 
阅读(<SPAN id="post_view_count">...</SPAN>) 评论(<SPAN 
id="post_comment_count">...</SPAN>)  <A href="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx?postid=2063847" 
rel="nofollow">编辑</A> <A onclick="AddToWz(2063847);return false;" href="http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html#">收藏</A></DIV></DIV>
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/2063847.js" type="text/javascript"></SCRIPT>
 
<DIV id="blog-comments-placeholder"></DIV>
<SCRIPT type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</SCRIPT>
 
<DIV class="commentform" id="comment_form">
<DIV id="divCommentShow"></DIV>
<DIV id="comment_nav"><SPAN id="span_refresh_tips"></SPAN><A id="lnk_RefreshComments" 
onclick="return RefreshCommentList();" href="javascript:void(0);">刷新评论</A><A 
onclick="return RefreshPage();" href="http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html#">刷新页面</A><A 
href="http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html#top">返回顶部</A></DIV>
<DIV id="comment_form_container"></DIV>
<SCRIPT type="text/javascript">
    if (typeof commentManager === 'undefined') {
        commentManager = new blogCommentManager();
    }
    commentManager.loadCommentForm();   
</SCRIPT>
 
<DIV class="ad_text_commentbox" id="ad_text_under_commentbox"></DIV>
<DIV id="site_nav_under"><A title="程序员的网上家园" href="http://www.cnblogs.com/" 
target="_blank">博客园首页</A><A title="程序员问答社区" href="http://q.cnblogs.com/" target="_blank">博问</A><A 
title="IT新闻" href="http://news.cnblogs.com/" target="_blank">新闻</A><A href="http://home.cnblogs.com/ing/" 
target="_blank">闪存</A><A href="http://job.cnblogs.com/" 
target="_blank">程序员招聘</A><A href="http://kb.cnblogs.com/" 
target="_blank">知识库</A></DIV>
<DIV id="ad_under_post_holder"></DIV>
<DIV class="c_ad_block" id="HistoryToday"></DIV></DIV></DIV></DIV></DIV><!-- left ends -->
	 <!-- right starts -->	 
<DIV id="right"><!-- 右侧工具部分 -->		 
<DIV id="right_content"><!--done--> 
<H1 class="listtitle" style="padding-top: 14px; padding-left: 42px;">公告</H1>
<DIV class="newsItem">
<DIV id="blog-news"></DIV></DIV>
<DIV id="calendar">
<DIV id="blog-calendar-block" style="display: none;">
<DIV id="blog-calendar"></DIV></DIV></DIV>
<DIV id="leftcontentcontainer">
<DIV id="blog-sidecolumn"></DIV></DIV></DIV><!-- //右侧工具部分 -->	 </DIV><!-- right ends -->
	 
<DIV class="clear"></DIV></DIV>
<DIV id="footer"><!--done--> Copyright ©2013 Braincol</DIV>
<SCRIPT src="Android%20NDK编程入门笔记%20-%20Braincol%20-%20博客园_files/google-analytics.js" type="text/javascript"></SCRIPT>
 </BODY></HTML>
